package com.tenton.netty.multicast;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;


/**
 * @ClassName: DataRecvHandler
 * @Description: UDP组播接收数据
 * @Author： tangdong
 * @Date： 2024/6/25
 */
@Slf4j
@SuppressWarnings("unused")
public class DataRecvHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    //PDXP长度
    private final static int PDXP_NUM = 1 + 2 + 4 + 4 + 4 + 4 + 1 + 4 + 2 + 4 + 2;
    //遥控指令长度
    private final static int CONTROL_NUM = 1 + 1 + 4 + 2 + 4;
    //数据传输头
    private final static int HEAD = 0xFC1D1ACF;
    //数据偏移量 + 数据传输头和描述长度
    private final static int HEAD_NUM = 5 + 4 + 28;

    public static AtomicInteger num = new AtomicInteger(0);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket msg) {

        ByteBuf buffer = msg.content();
        //解析PDXP头 32位
        if (buffer.readableBytes() < PDXP_NUM) {
            //数据长度不满足32个字节，等待下一包
            buffer.resetReaderIndex();
            return;
        }
        //头部数据不等
        if (buffer.readIntLE() !=  HEAD) {
            //头部数据不等，等待下一包
            buffer.resetReaderIndex();
            return;
        }

        //版本VER用于标识协议版本，用b7、b6表示，其余位保留。b7b6=[10]
        byte ver = buffer.readByte();
        //任务标志MID
        short mid = buffer.readShortLE();
        //信源SID
        int sid = buffer.readIntLE();
        //信宿DID地址
        int did = buffer.readIntLE();
        //数据标志BID
        int bid = buffer.readIntLE();
        //包序号No
        int no = buffer.readIntLE();
        //数据处理标志FLAG
        byte flag = buffer.readByte();
        //保留字段Field
        int field = buffer.readIntLE();
        //发送日期DATE
        short date = buffer.readShortLE();
        //发送时标TIME
        int time = buffer.readIntLE();
        //数据域长度L
        short l = buffer.readShortLE();
        if (buffer.readableBytes() < l) {
            //数据长度不满足数据域长度L，等待下一包
            buffer.resetReaderIndex();
            return;
        }
        //跳过5字节偏移量
        buffer.skipBytes(5);
        //帧CRC
        short crc = buffer.readShortLE();
    }

}
